package com.example.sandbox.controller.channel.uupay;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.sandbox.controller.notice.TransferComponent;
import com.example.sandbox.dto.Enum.Currency;
import com.example.sandbox.dto.TransferMerchantRequest;
import com.example.sandbox.dto.domain.PayOrder;
import com.example.sandbox.dto.domain.TransferOrder;
import com.example.sandbox.mapper.TransferOrderMapper;
import com.example.sandbox.util.AmountUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Executor;

@Slf4j
@RestController
public class UupayTransferController {

    @Autowired
    private TransferOrderMapper transferOrderMapper;
    @Autowired
    private TransferComponent transferComponent;
    @Autowired
    private Executor generalExecutor;

    @GetMapping("/api/v1/sandbox/transfer/simulatePaymentS/{transferId}")
    public String simulatePaymentS(@PathVariable("transferId") String transferId) throws IOException {
        if (StringUtils.isEmpty(transferId)) {
            return "请传入订单号";
        }
        QueryWrapper<TransferOrder> query = new QueryWrapper<>();
        query.eq("transfer_id", transferId).eq("state", PayOrder.STATE_ING);
        TransferOrder transferOrder = transferOrderMapper.selectOne(query);
        if (Objects.isNull(transferOrder)) {
            return "订单不存在或订单状态不在代付中";
        }
        transferOrder.setState(PayOrder.STATE_SUCCESS);
        int isUpdated = transferOrderMapper.update(transferOrder, query);
        if (isUpdated > 0) {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("accountNo", transferOrder.getAccountNo()); // 账户编号
            dataMap.put("amount", AmountUtil.convertCent2Dollar(transferOrder.getAmount(), Currency.BRL.getCurrency())); // 支付金额（3位小数）
            dataMap.put("createdAt", transferOrder.getCreatedAt().getTime()); // 订单创建时间, 13位时间戳
            dataMap.put("currency", transferOrder.getCurrency()); // 三位货币代码, 巴西币 BRL
            dataMap.put("successTime", System.currentTimeMillis()); // 订单支付成功时间, 13位时间戳
            dataMap.put("reqTime", System.currentTimeMillis()); // 订单支付成功时间, 13位时间戳
            dataMap.put("mchNo", transferOrder.getMchNo()); // 商户号
            dataMap.put("mchOrderNo", transferOrder.getMchOrderNo()); // 商户传入的订单号
            dataMap.put("state", PayOrder.STATE_SUCCESS); // 支付订单状态
            dataMap.put("transferDesc", transferOrder.getTransferDesc()); // 转账描述
            dataMap.put("transferId", transferOrder.getTransferId()); // 系统支付订单号
            dataMap.put("accountName", transferOrder.getAccountName()); // 账户名称
            dataMap.put("sign", ""); // 账户名称
            generalExecutor.execute(() -> {
                try {
                    transferComponent.notifyPaymentPay(dataMap, transferOrder.getNotifyUrl());
                } catch (IOException e) {
                    log.error("uu - 代付成功通知异常 url:{}", transferOrder.getNotifyUrl());
                    throw new RuntimeException(e);
                }
            });

            return "操作成功,代付成功";
        }
        return "操作失败";
    }

    @GetMapping("/api/v1/sandbox/transfer/simulatePaymentF/{transferId}")
    public String simulatePaymentF(@PathVariable("transferId") String transferId) throws IOException {
        if (StringUtils.isEmpty(transferId)) {
            return "请传入订单号";
        }
        QueryWrapper<TransferOrder> query = new QueryWrapper<>();
        query.eq("transfer_id", transferId).eq("state", TransferOrder.STATE_ING);
        TransferOrder transferOrder = transferOrderMapper.selectOne(query);
        if (Objects.isNull(transferOrder)) {
            return "订单不存在或订单状态不在代付中";
        }
        transferOrder.setState(TransferOrder.STATE_FAIL);
        int isUpdated = transferOrderMapper.update(transferOrder, query);
        if (isUpdated > 0) {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("accountNo", transferOrder.getAccountNo()); // 账户编号
            dataMap.put("amount", AmountUtil.convertCent2Dollar(transferOrder.getAmount(), Currency.BRL.getCurrency())); // 支付金额（3位小数）
            dataMap.put("createdAt", transferOrder.getCreatedAt().getTime()); // 订单创建时间, 13位时间戳
            dataMap.put("currency", transferOrder.getCurrency()); // 三位货币代码, 巴西币 BRL
            dataMap.put("successTime", System.currentTimeMillis()); // 订单支付成功时间, 13位时间戳
            dataMap.put("reqTime", System.currentTimeMillis()); // 订单支付成功时间, 13位时间戳
            dataMap.put("mchNo", transferOrder.getMchNo()); // 商户号
            dataMap.put("mchOrderNo", transferOrder.getMchOrderNo()); // 商户传入的订单号
            dataMap.put("state", PayOrder.STATE_FAIL); // 支付订单状态
            dataMap.put("transferDesc", transferOrder.getTransferDesc()); // 转账描述
            dataMap.put("transferId", transferOrder.getTransferId()); // 系统支付订单号
            dataMap.put("accountName", transferOrder.getAccountName()); // 账户名称
            dataMap.put("sign", ""); // 账户名称
            generalExecutor.execute(() -> {
                try {
                    transferComponent.notifyPaymentPay(dataMap, transferOrder.getNotifyUrl());
                } catch (IOException e) {
                    log.error("uu - 代付失败通知异常 url:{}", transferOrder.getNotifyUrl());
                    throw new RuntimeException(e);
                }
            });
            return "操作成功,代付失败";
        }
        return "操作失败";
    }

    @PostMapping("/api/v1/pay/brazil/transfer/query")
    public Map queryOrder(@RequestBody TransferMerchantRequest request) {

        if (StringUtils.isEmpty(request.getTransferId()) && StringUtils.isEmpty(request.getMchOrderNo())) {
            Map map = new HashMap();
            map.put("提示", "商户订单号，与支付订单号不可同时为空");
            return map;
        }
        String transferId = (request.getTransferId() != null && !request.getTransferId().isEmpty()) ? request.getTransferId() : "";
        String mchOrderNo = (request.getMchOrderNo() != null && !request.getMchOrderNo().isEmpty()) ? request.getMchOrderNo() : "";
        QueryWrapper<TransferOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mch_no", request.getMchNo());
        queryWrapper.eq(StringUtils.isNotEmpty(transferId), "transfer_id", transferId);
        queryWrapper.eq(StringUtils.isNotEmpty(mchOrderNo), "mch_order_no", mchOrderNo);
        TransferOrder transferOrder = transferOrderMapper.selectOne(queryWrapper);
        if (Objects.isNull(transferOrder)) {
            Map map = new HashMap();
            map.put("提示", "订单不存在");
            return map;
        }
        Map<String, Object> responseMap = new HashMap<>();

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("transferId", transferOrder.getTransferId()); // 系统支付订单号
        dataMap.put("mchNo", transferOrder.getMchNo()); // 商户号
        dataMap.put("mchOrderNo", transferOrder.getMchOrderNo()); // 商户传入的订单号
        dataMap.put("amount", AmountUtil.convertCent2Dollar(transferOrder.getAmount(), Currency.BRL.getCurrency())); // 支付金额（3位小数）
        dataMap.put("currency", transferOrder.getCurrency()); // 三位货币代码, 巴西币 BRL
        dataMap.put("accountNo", transferOrder.getAccountNo()); // 账户编号
        dataMap.put("accountName", transferOrder.getAccountName()); // 账户名称
        dataMap.put("bankName", transferOrder.getBankName()); // 银行名称
        dataMap.put("transferDesc", transferOrder.getTransferDesc()); // 转账描述
        dataMap.put("state", transferOrder.getState()); // 支付订单状态
        dataMap.put("successTime", System.currentTimeMillis()); // 订单支付成功时间, 13位时间戳
        dataMap.put("createdAt", transferOrder.getCreatedAt().getTime()); // 订单创建时间, 13位时间戳

        responseMap.put("code", 0);
        responseMap.put("msg", "SUCCESS");
        responseMap.put("data", dataMap);
        responseMap.put("sign", "557B1724497D5792813CA573D96A23DB"); // 这里的签名根据实际情况生成

        return responseMap;
    }
}